package cn.seaboot.admin.reverse.manager;

import cn.seaboot.admin.reverse.bean.DataTable;
import cn.seaboot.flake.entity.MappingTable;
import cn.seaboot.flake.entity.NormTable;
import cn.seaboot.admin.reverse.service.DataService;
import cn.seaboot.admin.reverse.service.MappingService;
import cn.seaboot.admin.reverse.service.NormService;
import org.springframework.stereotype.Service;
import cn.seaboot.flake.reverse.NormToMappingConverter;

import javax.annotation.Resource;
import java.util.List;

/**
 * @author Mr.css
 * @version 2020-12-04 10:28
 */
@Service
public class MappingManager {

    @Resource
    private DataService dataService;

    @Resource
    private DataToNormConverter dataToNormConverter;

    @Resource
    private NormService normService;

    @Resource
    private MappingService mappingService;

    private final NormToMappingConverter normToMappingConverter = new NormToMappingConverter();

    /**
     * 重建数据映射信息
     *
     * @param schemaName 数据库名称
     */
    public void rebuildTable(String schemaName) {
        dataService.initAllTableInfo(schemaName);
        normService.deleteAll(schemaName);
        mappingService.deleteAll(schemaName);

        List<DataTable> tables = dataService.queryAllDataTable(schemaName);
        for (DataTable table: tables) {
            NormTable normTable = dataToNormConverter.dataTableToNormTable(table);
            MappingTable mappingTable = normToMappingConverter.normTableToMappingTable(normTable);

            normService.saveNormTables(normTable);
            mappingService.saveMappingTable(mappingTable);
        }
    }

    /**
     * 重建数据映射信息
     *
     * @param schemaName 数据库名称
     * @param tableName  表名
     */
    public void rebuildTable(String schemaName, String tableName) {
        dataService.initTableInfo(schemaName, tableName);
        DataTable dataTable = dataService.queryDataTable(schemaName, tableName);
        NormTable normTable = dataToNormConverter.dataTableToNormTable(dataTable);
        MappingTable mappingTable = normToMappingConverter.normTableToMappingTable(normTable);
        normService.delete(schemaName, tableName);
        mappingService.delete(schemaName, tableName);
        normService.saveNormTables(normTable);
        mappingService.saveMappingTable(mappingTable);
    }
}
